<template>
  <div class="h-screen flex flex-col text-[#262626] text-[14px] gap-1">
    <div v-if="isMac() && isElectron()" class="mac-titlebar"></div>
    <div class="overflow-auto flex-auto bg-[#ffffff]">
      <visitType
        v-show="showVisitType && !haveDefaultTarget"
        v-model:model-value="visitInfo.targetType"
      />
      <customCell
        title="客户"
        class="cursor-pointer"
        placeholder="请输入并选择客户名称"
        v-model:value="visitInfo.customerName"
        :isLink="true"
        :required="true"
        :readOnly="true"
        v-if="visitInfo.targetType === CommunicationTargetType.Customer"
        @click="showSelectCustomerView"
      />
      <customCell
        title="商机"
        placeholder="请输入并选择商机名称"
        v-model:value="visitInfo.opportunityName"
        :isLink="true"
        :required="true"
        :readOnly="true"
        v-if="visitInfo.targetType === CommunicationTargetType.Opportunity"
        @click="showSelectBusinessOpportunityView"
      />

      <customCell
        v-model:value="visitInfo.stageName"
        title="沟通环节"
        placeholder="选择沟通环节"
        :isLink="true"
        :required="true"
        :readOnly="true"
        @click="showTagActionSheet = true"
      />

      <customCell
        v-model:value="visitInfo.subject"
        title="沟通主题"
        placeholder="输入沟通主题"
        :maxlength="50"
        :required="true"
      />

      <div class="flex flex-col pt-4 pb-2 pl-4 bg-white">
        <div class="flex flex-row items-center mb-4">
          <p class="text-[#262626] text-[14px]">沟通时间</p>
          <div class="bg-red-500 rounded-full w-[4px] h-[4px] ml-2"></div>
        </div>

        <div class="flex flex-row items-center">
          <div :class="`w-[130px]  cursor-pointer`" @click="onShowStartDatePicker(0)">
            <div v-if="startTime" :class="`flex flex-col items-center`">
              <div class="text-lg font-bold">
                {{ startTime.slice(11, 11 + 5) }}
              </div>
              <div>{{ startTime.slice(0, 10) }}</div>
            </div>
            <div v-else>开始日期时间</div>
          </div>
          <img class="w-2 ml-[40px] mr-[24px]" src="@/icons/svg/orderVisit/to_icon.svg" />
          <div :class="`w-[150px] cursor-pointer`" @click="onShowStartDatePicker(1)">
            <div v-if="endTime" :class="`flex flex-col items-center`">
              <div class="text-lg font-bold">
                {{ endTime.slice(11, 11 + 5) }}
              </div>
              <div>{{ endTime.slice(0, 10) }}</div>
            </div>
            <div v-else>结束日期时间</div>
          </div>
        </div>
      </div>

      <div class="bg-white pt-4 text-[#262626] text-[14px]" ref="attenderRef">
        <div class="flex flex-row items-center pl-4 mb-2">
          <p>我方参会人</p>
          <div class="bg-red-500 rounded-full w-[4px] h-[4px] ml-2"></div>
        </div>
        <van-cell isLink :onclick="pushInnerAttendList">
          <span v-show="innerAttendList.length > 0" class="text-[#262626] mr-3"
            >{{ innerAttendList.length }}人</span
          >
          <span>请选择</span>
        </van-cell>
        <div class="felx-1 h-[0.5px] bg-gray-200" />
      </div>

      <div class="bg-white pt-4 text-[#262626] text-[14px]" v-if="isToB">
        <div class="flex flex-row items-center pl-4 mb-2">
          <p>客户参会人</p>
        </div>
        <van-cell :border="true" isLink :onclick="pushCustomerAttendList">
          <span v-show="customerAttendList.length > 0" class="text-[#262626] mr-3"
            >{{ customerAttendList.length }}人</span
          >
          <span>请选择</span>
        </van-cell>
        <div class="felx-1 h-[0.5px] bg-gray-200" />
      </div>

      <customCell
        v-model:value="visitInfo.onlineMeetUrl"
        title="线上沟通链接"
        placeholder="输入在线会议网址"
        :maxlength="200"
        type="textarea"
      />

      <customCell
        title="线下沟通地址"
        v-model:value="visitInfo.location"
        placeholder="添加地点"
        :maxlength="100"
        :autocomplete="true"
        :querySearchName="querySearchPlaceName"
      />

      <customCell
        title="其他信息"
        v-model:value="visitInfo.description"
        placeholder="添加描述"
        type="textarea"
        :maxlength="2000"
      />
    </div>

    <div v-if="!isKeyboardOpen" class="px-6 pt-5 pb-10 shadow-inner">
      <van-button
        :loading="onSubmitLoading"
        :disabled="onSubmitLoading"
        type="primary"
        color="#436BFF"
        size="large"
        @click="onSubmit"
        >安排沟通</van-button
      >
    </div>
  </div>

  <van-popup
    v-model:show="showDatePicker"
    round
    close-on-click-overlay
    position="bottom"
    safe-area-inset-bottom
  >
    <chooseTimeView
      :key="pickerKey"
      :start-date="startTime"
      :end-date="endTime"
      :edit-index="pickerEditIndex"
      @onConfirm="onConfirmTime"
      @onCancel="showDatePicker = false"
    />
  </van-popup>

  <van-action-sheet
    v-model:show="showTagActionSheet"
    :actions="currentStagesArr"
    cancel-text="取消"
    @select="onSelectTag"
  />

  <SelectCustomerView ref="selectCustomerRef" @onConfirm="onConfirmCustomer" />

  <SelectBusinessOpportunityView
    ref="selectBusinessOpportunityRef"
    @onConfirm="onConfirmBusinessOpportunity"
  />
</template>

<script setup lang="ts">
import { computed, ComputedRef, onMounted, ref } from "vue";
import { CommunicationTargetType, VisitInfo } from "./type";
import { searchAMapAPI, searchCustomerAttendAPI } from "@/services/orderVisit";
import customCell from "./components/customCell.vue";
import dayjs from "dayjs";
import chooseTimeView from "./components/chooseTimeView.vue";
import { useCommonStore, useOrderVisitStore } from "@/store";
import { useRoute, useRouter } from "vue-router";
import { closeToast, showLoadingToast, showToast } from "vant";
import { closeWindow } from "@/utils/electronTool";
import { isElectron, isMac, isAndroid } from "@/utils/platformTool";
import { useKeyboard } from "@/composables/useKeyboard";
import visitType from "./components/visitType.vue";
import SelectCustomerView from "../../components/customerView/SelectCustomerView.vue";
import SelectBusinessOpportunityView from "../../components/businessOpportunityView/SelectBusinessOpportunityView.vue";

const store = useOrderVisitStore();
const commonStore = useCommonStore();

const router = useRouter();
const route = useRoute();

const visitInfo: ComputedRef<VisitInfo> = computed(() => store.visitInfo);

const startTime = ref(visitInfo.value.upcomingStartTime);
const endTime = ref(visitInfo.value.upcomingEndTime);

const showDatePicker = ref(false);
const pickerKey = ref(1);
const pickerEditIndex = ref(0);
const keepLive = ref(false);

const { isOpen: isKeyboardOpen } = useKeyboard({
  onOpen: (h: number) => {
    console.log("Keyboard open height:", h);
  },
  onClose: () => {
    console.log("Keyboard closed");
  },
  threshold: 80,
});

onMounted(() => {
  if (alreadyInit.value) return;
  store.alreadyInit = true;
  init();
});

const isEdit = ref(false);

const alreadyInit = computed(() => store.alreadyInit);

// 是否存在商机
const enableBusinessOpportunity = computed(() => commonStore.enableBusinessOpportunity);
const cp_funcPoints = computed(() => commonStore.funcPoints);

// 是否为ToB类型
const isToB = computed(() => commonStore.isToB);

// 商机沟通环节
const businessOpportunityStages = computed(() => store.businessOpportunityStages);
// 客户沟通环节
const customerCommunicationStages = computed(() => store.customerCommunicationStages);
// 是否存在沟通流程
const existCommunicationProcess = computed(
  () => customerCommunicationStages.value.length > 0
);

// 是否展示类型切换： 有商机 & 有沟通流程
const showVisitType = computed(() => {
  return enableBusinessOpportunity.value && existCommunicationProcess.value;
});

async function init() {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
  });
  await commonStore.getUserInfoAction();
  store.getOuterFiledPartnerAction();
  store.getCustomerCommunicationStagesAction();
  commonStore.searchCustomerTypeAction();
  if (cp_funcPoints.value.length === 0) {
    await commonStore.getFuncpPointsAction();
  } else {
    commonStore.getFuncpPointsAction();
  }

  checkAttenderAnchor();
  const { scheduleId } = route.query;
  if (scheduleId) {
    await initEditVisitInfo(scheduleId as string);
  } else {
    await initCreateVisitInfo();
  }
  closeToast();
}
async function initCreateVisitInfo() {
  // 查询自己信息并添加到内部参会人中
  if (!store.anchorAttender) {
    await store.searchSelfInfoAction();
  }
  setDefaultTarget();
  // 如果是客户
  if (
    currentStagesArr.value.length === 1 &&
    visitInfo.value.targetType === CommunicationTargetType.Customer
  ) {
    visitInfo.value.stageName = currentStagesArr.value[0].name;
    visitInfo.value.stageId = currentStagesArr.value[0].id;
  }

  if (visitInfo.value.opportunityId.length > 0) {
    visitInfo.value.targetType = CommunicationTargetType.Opportunity;
  }

  if (visitInfo.value.customerId.length > 0) {
    visitInfo.value.targetType = CommunicationTargetType.Customer;
  }
}

const haveDefaultTarget = ref(false);
function setDefaultTarget() {
  console.log("setDefaultTarget");
  let { customerId, name, opportunityId } = route.query;

  visitInfo.value.targetType = enableBusinessOpportunity.value
    ? CommunicationTargetType.Opportunity
    : CommunicationTargetType.Customer;

  if (customerId?.length > 0) {
    visitInfo.value.customerId = customerId as string;
    visitInfo.value.customerName = name as string;
    visitInfo.value.targetType = CommunicationTargetType.Customer;
    synthesisSubject();
    autoAddCustomerAttendIfNeeded();
    haveDefaultTarget.value = true;
  }
  if (opportunityId?.length > 0 && enableBusinessOpportunity.value) {
    visitInfo.value.opportunityId = opportunityId as string;
    visitInfo.value.opportunityName = name as string;
    visitInfo.value.targetType = CommunicationTargetType.Opportunity;
    updateCustomerCommunicationStages();
    synthesisSubject();
    autoAddCustomerAttendIfNeeded();
    haveDefaultTarget.value = true;
  }
}

async function initEditVisitInfo(scheduleId: string) {
  isEdit.value = true;
  // 初始化过了，不用再重新赋值
  if (store.alreayMapVisitInfo) return;
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
  });
  await store.getVisitDetailAction(scheduleId);
  await updateCustomerCommunicationStages();
  startTime.value = visitInfo.value.upcomingStartTime;
  endTime.value = visitInfo.value.upcomingEndTime;
  store.tempSalesMateCustomerName = visitInfo.value.customerName;

  visitInfo.value.targetType =
    visitInfo.value.opportunityId.length > 0
      ? CommunicationTargetType.Opportunity
      : CommunicationTargetType.Customer;
  closeToast();
}

// 沟通环节
const showTagActionSheet = ref(false);

function onSelectTag(v: { name: string; id: string }) {
  visitInfo.value.stageId = v.id;
  visitInfo.value.stageName = v.name;
  showTagActionSheet.value = false;
  synthesisSubject();
}

async function autoAddCustomerAttendIfNeeded() {
  if (isToB.value) return;
  // 查询客户列表，如果客户列表中存在，则自动添加到客户参会人中

  console.log("isToB.value: ", isToB.value);

  let isCustomer = visitInfo.value.targetType === CommunicationTargetType.Customer;
  const tempCustomerId =
    (isCustomer ? visitInfo.value.customerId : visitInfo.value.customerIdOfOpportunity) ||
    "";

  if (tempCustomerId.length === 0) {
    return;
  }

  const data = await searchCustomerAttendAPI(tempCustomerId);

  console.log("autoAddCustomerAttendIfNeeded data: ", data);
  const customerContacts = data.customerContacts || [];

  if (customerContacts.length === 0) {
    console.warn("自动添加客户参会人失败,客户参会人列表为0.");
    return;
  }
  const defaultAttend = customerContacts.map((v) => {
    return {
      name: v.name,
      contactId: v.id,
      checked: true,
    };
  })[0];
  store.customerAttendList = [defaultAttend];
  console.log("默认添加客户参会人 ", defaultAttend);
}

function clearTarget() {
  visitInfo.value.opportunityId = "";
  visitInfo.value.opportunityName = "";
  visitInfo.value.customerIdOfOpportunity = "";
  visitInfo.value.customerId = "";
  visitInfo.value.customerName = "";
  visitInfo.value.stageId = "";
  visitInfo.value.stageName = "";
  visitInfo.value.subject = "";
  store.customerAttendList = [];
}

// 当前使用的沟通环节列表
const currentStagesArr = computed(() => {
  if (visitInfo.value.targetType === CommunicationTargetType.Opportunity) {
    return businessOpportunityStages.value;
  }
  return customerCommunicationStages.value;
});

async function updateCustomerCommunicationStages() {
  if (visitInfo.value.targetType === CommunicationTargetType.Customer) {
    store.businessOpportunityStages = [];
    return;
  }
  store.businessOpportunityStages = await store.getStagesAction({
    type: 2,
    targetId: visitInfo.value.opportunityId,
  });
}

// 选择客户
const selectCustomerRef = ref();

// 展示显示客户列表
function showSelectCustomerView() {
  selectCustomerRef.value.show();
}

// 选择客户
function onConfirmCustomer(v) {
  clearTarget();
  visitInfo.value.customerId = v.customerId;
  visitInfo.value.customerName = v.name;
  updateCustomerCommunicationStages();
  synthesisSubject();
  autoAddCustomerAttendIfNeeded();
}

// 选择商机
const selectBusinessOpportunityRef = ref();
// 展示显示商机列表
function showSelectBusinessOpportunityView() {
  selectBusinessOpportunityRef.value.show();
}

// 选择商机
function onConfirmBusinessOpportunity(v) {
  clearTarget();
  visitInfo.value.opportunityId = v.id;
  visitInfo.value.opportunityName = v.name;
  visitInfo.value.flowId = v.flowId;
  visitInfo.value.customerIdOfOpportunity = v.customerId;
  updateCustomerCommunicationStages();
  synthesisSubject();
  autoAddCustomerAttendIfNeeded();
}

function addCacheAdress(v) {
  if (store.cacheAdressList.some((item) => item === v)) {
    return;
  }
  store.cacheAdressList.push(v);
}

// 合成标题
function synthesisSubject() {
  if (visitInfo.value.stageName.length <= 0) return;

  if (
    visitInfo.value.opportunityName.length === 0 &&
    visitInfo.value.customerName.length === 0
  )
    return;

  visitInfo.value.subject =
    (visitInfo.value.opportunityName || visitInfo.value.customerName) +
    "-" +
    visitInfo.value.stageName;
}

function onShowStartDatePicker(editIndex: number) {
  pickerEditIndex.value = editIndex;
  pickerKey.value += 1;
  showDatePicker.value = true;
}

function onConfirmTime(start: any, end: any) {
  showDatePicker.value = false;
  startTime.value = start;
  endTime.value = end;
  visitInfo.value.upcomingStartTime = startTime.value;
  visitInfo.value.upcomingEndTime = endTime.value;
  console.log("onConfirmTime: ", startTime.value, endTime.value);
}

const attenderRef = ref();
function checkAttenderAnchor() {
  if (store.anchorAttender) {
    store.anchorAttender = false;
    attenderRef.value.scrollIntoView({
      behavior: "smooth",
      block: "center",
      inline: "center",
    });
  }
}

function pushCustomerAttendList() {
  let isCustomer = visitInfo.value.targetType === CommunicationTargetType.Customer;
  const customerId =
    (isCustomer ? visitInfo.value.customerId : visitInfo.value.customerIdOfOpportunity) ||
    "";

  console.log("customerId: ", customerId);

  if (customerId?.length === 0) {
    showToast(isCustomer ? "请先选择沟通客户" : "请先选择商机");
    return;
  }

  keepLive.value = true;
  store.anchorAttender = true;
  router.push({
    name: "customerList",
    query: { customerId: customerId },
  });
}

function pushInnerAttendList() {
  keepLive.value = true;

  store.anchorAttender = true;
  router.push({ name: "attendList" });
}

const innerAttendList = computed(() => {
  let array = store.innerAttendList.filter((v: { checked: any }) => v.checked);
  return array;
});
const customerAttendList = computed(() => {
  let array = store.customerAttendList.filter((v: { checked: any }) => v.checked);
  for (const element of array) {
    element.attendeeType = "CUSTOMER_ATTENDEE";
  }
  return array;
});
function validate() {
  if (visitInfo.value.targetType === CommunicationTargetType.Opportunity) {
    if (visitInfo.value.opportunityName.length === 0) {
      showToast("请选择商机");
      return false;
    }
  }

  if (visitInfo.value.targetType === CommunicationTargetType.Customer) {
    if (visitInfo.value.customerName.length === 0) {
      showToast("请选择沟通客户");
      return false;
    }
  }

  if (visitInfo.value.stageId.length === 0) {
    showToast("请选择沟通环节");
    return false;
  }
  if (visitInfo.value.subject.length === 0) {
    showToast("请输入沟通主题");
    return false;
  }
  if (startTime.value.length === 0) {
    showToast("请选择开始日期时间");
    return false;
  }
  if (endTime.value.length === 0) {
    showToast("请选择结束日期时间");
    return false;
  }
  if (innerAttendList.value.length === 0) {
    showToast("请选择内部参会人员");
    return false;
  }

  if (dayjs(startTime.value).isBefore(dayjs())) {
    showToast("开始日期时间不能早于当前时间");
    return false;
  }
  return true;
}

async function onSubmit() {
  if (!validate()) {
    return;
  }
  let innerArray = innerAttendList.value;
  let customerArray = customerAttendList.value;

  console.log("onSubmit innerArray: ", innerArray);
  console.log("onSubmit customerArray: ", customerArray);

  let innerArray2 = innerArray.map((element) => {
    let v = {
      name: element.name,
      attendeeType: element.participantType,
    };

    if (element.participantType === "EXTERNAL_PARTNER") {
      v.contactId = element.partnerId;
    } else {
      v.ssoUserId = element.ssoUserId;
    }
    return v;
  });

  let customerArray2 = customerArray.map((element) => {
    return {
      name: element.name,
      contactId: element.contactId,
      attendeeType: "CUSTOMER_ATTENDEE",
    };
  });

  visitInfo.value.participantList = [...innerArray2, ...customerArray2];
  visitInfo.value.upcomingStartTime = startTime.value;
  visitInfo.value.upcomingEndTime = endTime.value;

  // 去除本地字段
  delete visitInfo.value.flowId;
  delete visitInfo.value.targetType;
  delete visitInfo.value.customerIdOfOpportunity;
  if (visitInfo.value.opportunityId?.length > 0) {
    delete visitInfo.value.customerName;
  }

  console.log("visitInfo.value: ", visitInfo.value);

  doApi(visitInfo.value);
}

const onSubmitLoading = ref(false);
async function doApi(v: VisitInfo) {
  onSubmitLoading.value = true;
  let res;
  if (isEdit.value) {
    res = await store.updateVisitRecordAction(v);
    if (res.confId) {
      showToast("编辑沟通成功");
    }
  } else {
    res = await store.createVisitRecordAction(v);
    if (res.confId) {
      showToast("安排沟通成功");
    }
  }
  onSubmitLoading.value = false;
  addCacheAdress(v.location);
  // 调用Flutter方法
  closePage();
}

function closePage() {
  if (isElectron()) {
    closeWindow();
  } else {
    window.flutter_inappwebview.callHandler("OrderVisitComplete", "success");
  }
}

// 搜索地点
async function querySearchPlaceName(query: String, cb: Function) {
  if (query.length === 0) return;
  if (query.length === 0) {
    cb(
      store.cacheAdressList.map((v: any) => {
        return { value: v };
      })
    );
    return;
  }
  const data = (await searchAMapAPI(query)) || [];
  const pois = data.pois || [];
  let result = [];
  result = pois.map((v: Object) => {
    return {
      value: v.cityname + v.adname + v.name,
    };
  });
  cb(result);
}
</script>

<style lang="less" scoped>
.test {
  font-weight: normal;
  text-shadow: 1px 1px 0 rgba(0, 0, 0, 0.2);
}

div {
  --van-divider-content-padding: 0;
  --van-divider-vertical-margin: 0;
}

/deep/ .van-badge--dot {
  width: 4px;
  height: 4px;
}

/deep/ .van-cell__value {
  text-align: left;
}

.order-visit-container {
  height: 100vh;
}
</style>
